function disableSubmit(finalResult,submitButtonId) {
	if(finalResult) {
		document.getElementById(submitButtonId).disabled = true;
		return finalResult;
	}else {
		return finalResult;
	}
}

function batchDelete(action,checkboxName,form){
    if (!hasOneChecked(checkboxName)){
            alert('请选择要操作的对象!');
            return;
    }
    if (confirm('确定执行[删除]操作?')){
        form.action = action;
        form.submit();
    }
}
function batchAdd(action,checkboxName,form){
    if (!hasOneChecked(checkboxName)){
            alert('请选择要操作的对象!');
            return;
    }
    form.action = action;
    form.submit();
}

function hasOneChecked(name){
    var items = document.getElementsByName(name);
    if (items.length > 0) {
        for (var i = 0; i < items.length; i++){
            if (items[i].checked == true){
                return true;
            }
        }
    } else {
        if (items.checked == true) {
            return true;
        }
    }
    return false;
}

function setAllCheckboxState(name,state) {
	var elms = document.getElementsByName(name);
	for(var i = 0; i < elms.length; i++) {
		elms[i].checked = state;
	}
}

function getReferenceForm(elm) {
	while(elm && elm.tagName != 'BODY') {
		if(elm.tagName == 'FORM') return elm;
		elm = elm.parentNode;
	}
	return null;
}

function changeSortAndPage(pageNumber,sortName)
{
	var sortColumns = document.forms[0].sortColumns.value;
	var sorts = sortColumns.split(" ");
	
	var column = sorts[0];
	var order = sorts.length > 1 ? sorts[1]:'asc';
	
	if(column == sortName){
		if(order == 'asc'){
			document.forms[0].sortColumns.value = sortName + ' ' + 'desc';
		}else{
			document.forms[0].sortColumns.value = sortName + ' ' + 'asc';
		}
	}else{
		document.forms[0].sortColumns.value = sortName + ' ' + 'asc';
	}
	document.forms[0].pageNumber.value = pageNumber
	document.forms[0].submit();
}
function changePageNumber(pageNumber)
{
	document.forms[0].pageNumber.value = pageNumber
	document.forms[0].submit();
}
function toggleSelection(obj, collection, firstElement){
	if (obj.className == 'btn btn-default'){	        		
		//if 'All' selected
		if ($(obj).attr('data-code') =='0'){	        			
			$(collection).removeClass('btn-default').addClass('btn-success');
		}
		else{
			obj.className = 'btn btn-success';	  
		}
	}
	else{	    
		//if 'All' unselected
		if ($(obj).attr('data-code') =='0'){
			$(collection).removeClass('btn-success').addClass('btn-default');
		}
		else{
			obj.className = 'btn btn-default';
			
		}
		$(firstElement).removeClass('btn-success').addClass('btn-default');
	}  
};

function addDatePicker(selector){
	$(selector).datetimepicker({
                weekStart: 0,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0,
                pickerPosition:'bottom-left'
            });
};

function addMonthPicker(selector){
	$(selector).datetimepicker({
                weekStart: 0,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 3,
                minView: 3,
                forceParse: 0,
                pickerPosition:'bottom-left'
            });
};

function addDateTimePicker(selector){
	$(selector).datetimepicker({
                weekStart: 0,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                forceParse: 0,
                pickerPosition:'bottom-left'
            });
};

function addTimePicker(selector){
	$(selector).datetimepicker({
                autoclose: 1,
                startView: 1,
                format:"hh:ii",
                pickerPosition:'bottom-left'
            });
};


function toggleIcon(selector){
	$(selector).click(function(){  
		var span = $(this).children('span:first');
		if (span.hasClass('glyphicon-plus')) {
			span.removeClass('glyphicon-plus').addClass('glyphicon-minus');
		}      	
		else{
			span.removeClass('glyphicon-minus').addClass('glyphicon-plus');
		}
    });
};

function addPaginator(selector, currentPage, totalPages){
	var options = {
		bootstrapMajorVersion: 3,
		alignment: "right",
	    currentPage: currentPage,
	    numberOfPages: 5,
	    totalPages: totalPages,	    
	    useBootstrapTooltip: true,//是否使用 bootstrap 自带的提示框
	    itemContainerClass: function (type, page, currentpage) {  //每项的类名
            //alert(type + "  " + page + "  " + currentpage)
            var classname = "p_item ";

            switch (type) {
                case "first":
                    classname += "p_first";
                    break;
                case "last":
                    classname += "p_last";
                    break;
                case "prev":
                    classname += "p_prev";
                    break;
                case "next":
                    classname += "p_next";
                    break;
                case "page":
                    classname += "p_page";
                    break;
            }

            if (page == currentpage) {
                classname += " active "
            }

            return classname;
        },
        itemTexts: function (type, page, current) {  //
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上页";
                case "next":
                    return "下页";
                case "last":
                    return "末页";
                case "page":
                    return page;
            }
        },
        tooltipTitles: function (type, page, current) {
            switch (type) {
                case "first": return "首页";
                case "prev": return "上页";
                case "next": return "下页";
                case "last": return "末页";
                case "page": return page === current ? "当前页数 " + page : "前往第 " + page + " 页"
            }
        },
	    onPageClicked: function(e,originalEvent,type,page){
	    	e.stopImmediatePropagation();            	
	    	var currentTarget = $(e.currentTarget);
	        var currentPage = currentTarget.bootstrapPaginator("getPages").current;
	        
	        if (currentPage != page){
	    		changePageNumber(page);
	    	}	    	
	    	return;
	    }
    }
    
    $(selector).bootstrapPaginator(options);
}

function addCustomPaginator(selector,formId,sortColumnId,pageNumberId,currentPage, totalPages,tabName){
	var options = {
		bootstrapMajorVersion: 3,
		alignment: "right",
	    currentPage: currentPage,
	    numberOfPages: 5,
	    totalPages: totalPages,	    
	    useBootstrapTooltip: true,//是否使用 bootstrap 自带的提示框
	    itemContainerClass: function (type, page, currentpage) {  //每项的类名
            //alert(type + "  " + page + "  " + currentpage)
            var classname = "p_item ";

            switch (type) {
                case "first":
                    classname += "p_first";
                    break;
                case "last":
                    classname += "p_last";
                    break;
                case "prev":
                    classname += "p_prev";
                    break;
                case "next":
                    classname += "p_next";
                    break;
                case "page":
                    classname += "p_page";
                    break;
            }

            if (page == currentpage) {
                classname += " active "
            }

            return classname;
        },
        itemTexts: function (type, page, current) {  //
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上页";
                case "next":
                    return "下页";
                case "last":
                    return "末页";
                case "page":
                    return page;
            }
        },
        tooltipTitles: function (type, page, current) {
            switch (type) {
                case "first": return "首页";
                case "prev": return "上页";
                case "next": return "下页";
                case "last": return "末页";
                case "page": return page === current ? "当前页数 " + page : "前往第 " + page + " 页"
            }
        },
	    onPageClicked: function(e,originalEvent,type,page){
	    	e.stopImmediatePropagation();            	
	    	var currentTarget = $(e.currentTarget);
	        var currentPage = currentTarget.bootstrapPaginator("getPages").current;
	        $("#currentTab").val(tabName);
	        if (currentPage != page){
	        	changeCustomPageNumber(formId,pageNumberId,page);
	    	}	    	
	    	return;
	    }
    }
    
    $(selector).bootstrapPaginator(options);
}

function changeCustomPageNumber(formId,pageNumberId,pageNumber)
{
	$(pageNumberId).val(pageNumber)
	$(formId).submit()
}
function showValidationError(field, message){
	$('[name='+ field + ']').after('<div class="alert alert-danger" style="padding:6px;margin-bottom:0px">' + message['' + field + ''] +'</div>');                	
}

function parseDDMMYYYY(element) {
	var datearray = element.split(" ");
	var date = datearray[0];
	
	var arr = date.split("/");
	if(arr.length == 3){
		return new Date(arr[2],(arr[1] - 1),arr[0]);
	}else{
		return null;
	}
}

/** 
* 时间对象的格式化 
*/  
Date.prototype.format = function(format)  
{  
/* 
* format="yyyy-MM-dd hh:mm:ss"; 
*/  
var o = {  
"M+" : this.getMonth() + 1,  
"d+" : this.getDate(),  
"h+" : this.getHours(),  
"m+" : this.getMinutes(),  
"s+" : this.getSeconds(),  
"q+" : Math.floor((this.getMonth() + 3) / 3),  
"S" : this.getMilliseconds()  
}  
  
if (/(y+)/.test(format))  
{  
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4  
- RegExp.$1.length));  
}  
  
for (var k in o)  
{  
if (new RegExp("(" + k + ")").test(format))  
{  
format = format.replace(RegExp.$1, RegExp.$1.length == 1  
? o[k]  
: ("00" + o[k]).substr(("" + o[k]).length));  
}  
}  
return format;  
}  


function Map() {  
    this.elements = new Array();  
    //获取MAP元素个数  
    this.size = function() {  
        return this.elements.length;  
    };  
    //判断MAP是否为空  
    this.isEmpty = function() {  
        return (this.elements.length < 1);  
    };  
    //删除MAP所有元素  
    this.clear = function() {  
        this.elements = new Array();  
    };  
    //向MAP中增加元素（key, value)   
    this.put = function(_key, _value) {  
        this.elements.push( {  
            key : _key,  
            value : _value  
        });  
    };  
    //删除指定KEY的元素，成功返回True，失败返回False  
    this.remove = function(_key) {  
        var bln = false;  
        try {  
            for (i = 0; i < this.elements.length; i++) {  
                if (this.elements[i].key == _key) {  
                    this.elements.splice(i, 1);  
                    return true;  
                }  
            }  
        } catch (e) {  
            bln = false;  
        }  
        return bln;  
    };  
    //获取指定KEY的元素值VALUE，失败返回NULL  
    this.get = function(_key) {  
        try {  
            for (i = 0; i < this.elements.length; i++) {  
                if (this.elements[i].key == _key) {  
                    return this.elements[i].value;  
                }  
            }  
        } catch (e) {  
            return null;  
        }  
    };  
    //获取指定索引的元素（使用element.key，element.value获取KEY和VALUE），失败返回NULL  
    this.element = function(_index) {  
        if (_index < 0 || _index >= this.elements.length) {  
            return null;  
        }  
        return this.elements[_index];  
    };  
    //判断MAP中是否含有指定KEY的元素  
    this.containsKey = function(_key) {  
        var bln = false;  
        try {  
            for (i = 0; i < this.elements.length; i++) {  
                if (this.elements[i].key == _key) {  
                    bln = true;  
                }  
            }  
        } catch (e) {  
            bln = false;  
        }  
        return bln;  
    };  
    //判断MAP中是否含有指定VALUE的元素  
    this.containsValue = function(_value) {  
        var bln = false;  
        try {  
            for (i = 0; i < this.elements.length; i++) {  
                if (this.elements[i].value == _value) {  
                    bln = true;  
                }  
            }  
        } catch (e) {  
            bln = false;  
        }  
        return bln;  
    };  
    //获取MAP中所有VALUE的数组（ARRAY）  
    this.values = function() {  
        var arr = new Array();  
        for (i = 0; i < this.elements.length; i++) {  
            arr.push(this.elements[i].value);  
        }  
        return arr;  
    };  
    //获取MAP中所有KEY的数组（ARRAY）  
    this.keys = function() {  
        var arr = new Array();  
        for (i = 0; i < this.elements.length; i++) {  
            arr.push(this.elements[i].key);  
        }  
        return arr;  
    };  
} 

function isPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

function getContextPath() {
    var pathName = document.location.pathname;
    var index = pathName.substr(1).indexOf("/");
    var result = pathName.substr(0,index+1);
    return result;
}
